//
//  EssencePictureView.swift
//  FM
//
//  Created by x on 2017/10/17.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

class EssencePictureView: UICollectionView {
    
    var model:Essence? {
        didSet {
            reloadData()
        }
    }
    
    
    private var pictureLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()

    init() {
        
        super.init(frame: CGRect.zero, collectionViewLayout: pictureLayout)
        
        translatesAutoresizingMaskIntoConstraints = false
        
        //1.注册cellpictureCellIdentifier
        register(pictureCollectionViewCell.self, forCellWithReuseIdentifier: pictureCellIdentifier)
        
        //设置相关的数据源
        dataSource = self
        delegate = self
        
        //设置cell的间隙
        pictureLayout.minimumLineSpacing = 10
        pictureLayout.minimumInteritemSpacing = 10
        
    }
    
    /// 计算配图的尺寸
    ///
    /// - Returns: 返回collectionView的size 和 item的Size
    func calculateImageSize() -> CGSize {//函数返回的类型是个元组
        
        /// 获取图片的数量
        let pictureCount = model?.images?.count
        //1.判断有没有图片
        if pictureCount == 0 || pictureCount == nil {
            return CGSize.zero
        }
        //2.判断只有一张图片则显示把图片的实际尺寸
        if pictureCount == 1 {
            //2.1取出缓存的图片
            let key = model?.imageURLS?.first?.absoluteString
            //print("key=======",key)
            let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: key)
            
            //设置Item的大小
            let scale = image!.size.height / image!.size.width
            
            let size = CGSize(width: 150 , height: 150*scale)
            
            
            pictureLayout.itemSize = size
            //2.2返回缓存图片的实际大小
            return size
        }
        //3.判断图片是不是有4张图片  计算田字格的大小
        let width = 90  //item的大小
        let margin = 10 //item之间的间距
        if pictureCount == 4 {
            let viewWidth = width * 2 + margin //整个田字格的大小
            //设置item的带下
            pictureLayout.itemSize = CGSize(width: width, height: width)
            
            return CGSize(width: viewWidth, height: viewWidth)
        }
        //4.如果是其他(多张 ) 计算九宫格的大小
        //2.3.5.6.7.8.9  这些数量的照片
        //4.1 计算九空格的列数
        let colNumber = 3
        //4.2计算行数
        let rowNumber = (pictureCount! - 1)/3 + 1
        //4.3计算collectionView的宽度
        let viewWidth = colNumber * width + (colNumber - 1) * margin
        //4.4 计算collectionView的高度
        let viewHeight = rowNumber * width + (rowNumber - 1) * margin
        
        //设置item的带下
        pictureLayout.itemSize = CGSize(width: width, height: width)
        
        return CGSize(width: viewWidth, height: viewHeight)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

private let pictureCellIdentifier = "pictureCellIdentifier"

extension EssencePictureView:UICollectionViewDelegate,UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return model?.imageURLS?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pictureCellIdentifier, for: indexPath) as! pictureCollectionViewCell
        cell.iconImageURL = model?.imageURLS?[indexPath.row] as URL?
        
        return cell
    }
}

/// 自定义collectionViewCell
private class pictureCollectionViewCell: UICollectionViewCell {
    
    var iconImageURL: URL? {
        didSet {
            iconImageView.sd_setImage(with: iconImageURL)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //添加子控件
        contentView.addSubview(iconImageView)
    
        //布局子控件
        var cons:[NSLayoutConstraint] = [NSLayoutConstraint]()
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[iconImageView]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["iconImageView":iconImageView])
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[iconImageView]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["iconImageView":iconImageView])
        
        contentView.addConstraints(cons)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 懒加载ImageView
    private lazy var iconImageView = UIImageView.imageWith(radios: 0, imageName: "")
    
}




























